package com.bvgol.examples.bio;/**
 * @Classname BIOServer
 * @Description TODO
 * @Date 2021/6/16 16:31
 * @Created by GUOCHEN
 */

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: my-spring-completely
 * @description: BIO模型 telnet通讯
 * @author: GUOCHEN
 * @create: 2021/06/16 16:31
 */

/**
 * 1.启动服务
 * 2.cmd -> Telnet 127.0.0.1 6666
 * 3.ctrl+]
 * 4.send message (send 为关键字)
 * 5.c 断开连接
 *
 *
 * BIO()传统的java io 模型 模型缺陷
 *  1.每个请求都需要创建独立的线程,与对应额客户端进行数据read,业务处理,数据write
 *  2.当并发数较大时,需要创建大量线程来处理连接,系统资源占用较大
 *  3.连接建立后,如果单签线程暂时没有数据可读,则线程就会阻塞在read操作上,造成线程资源浪费
 */
public class   BIOServer {

    String  s = new String("ssss");


    public static void main(String[] args) throws IOException {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        while (true){
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }

    }


    private static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        try {

            InputStream inputStream = socket.getInputStream();
            while(true){
                int read = inputStream.read(bytes);
                if(read!= -1){

                    System.out.println(Thread.currentThread().getName()+"------>"+new String(bytes,0,read));
                }
                else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和client 的连接对象");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
